package com.bsh.api;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bsh.api.Exception.ApiException;
import com.bsh.service.ApiSmsService;
import com.bsh.service.SmsService;
import com.bsh.service.UserService;
import com.bsh.utils.ApiMessage;
import com.bsh.utils.Des3Utils;
import com.bsh.utils.IpUtil;

/**
 * 短信相关API
 * 
 * @author gsh
 * @since 0.0.1
 * 
 */
@Controller
public class ApiSMSController {
	private static Logger log = LoggerFactory.getLogger(ApiSMSController.class);
	@Autowired
	SmsService smsServ;
	@Autowired
	UserService servUser;
	@Autowired
	HttpServletRequest request;
	@Autowired
	HttpServletResponse response;
	@Autowired
	ApiSmsService apiSmsService;


	
	/**
	 * 发送验证码(图片验证码版本)
	 * 
	 * @param paramStr
	 * @return
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/api/v1/sms/send", method = { RequestMethod.POST })
	@ResponseBody
	public ApiMessage apiLogin(@RequestParam String paramStr) {
		ApiMessage msg = new ApiMessage();
		try {
			paramStr=Des3Utils.decode(paramStr);
			JSONObject dto = (JSONObject) JSON.parse(paramStr);
			dto.put("ip", IpUtil.getIpAddr(request));
			msg = apiSmsService.sendSms(dto);
		} catch (ApiException e) {
			msg.setCode(e.getCode());
			msg.setMessage(e.getMessage());
		} catch (Exception e) {
			msg = new ApiMessage("400", "请求不正确");
			e.printStackTrace();
		} finally {
			return msg;
		}

	}
	
	
	/**
	 * 发送验证码
	 * 
	 * @param paramStr
	 * @return
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/api/v1/sms/getUuid", method = { RequestMethod.POST })
	@ResponseBody
	public ApiMessage getUuid(@RequestParam String paramStr) {
		ApiMessage msg = new ApiMessage();
		try {
			JSONObject dto = (JSONObject) JSON.parse(paramStr);
			dto.put("server_ip", ApiUtils.getUrl(request));
			dto.put("ip", IpUtil.getIpAddr(request));
			msg = apiSmsService.getUuid(dto);
		} catch (ApiException e) {
			msg.setCode(e.getCode());
			msg.setMessage(e.getMessage());
		} catch (Exception e) {
			msg = new ApiMessage("400", "请求不正确");
			e.printStackTrace();
		} finally {
			return msg;
		}

	}
	
	
}
